Critical [v1.0.38.04+]


Prevents the current thread from being interrupted by other threads.

Critical [, Off]

If the first parameter is omitted (or the word On), the current thread is made critical, meaning that it cannot be interrupted by another thread. If the first parameter is the word Off, the current thread immediately becomes interruptible, regardless of the settings of "Thread Interrupt".

Unlike high-priority threads, events that occur during a critical thread are not discarded. For example, if the user presses a hotkey while the current thread is critical, the hotkey is buffered indefinitely until the current thread finishes or becomes noncritical, at which time the hotkey is launched as a new thread.

A critical thread will be interrupted in emergencies. Emergencies consist of the OnExit subroutine and any OnMessage() function that monitors a message number less than 0x312. To avoid these interruptions, temporarily disable such functions.

When buffered events are waiting to start new threads, using "Critical Off" will not result in an immediate interruption of the current thread. Instead, an average of 5 milliseconds will pass before an interruption occurs. This makes it more than 99.999% likely that at least one line after "Critical Off" will execute before an interruption. You can force interruptions to occur immediately by means of a delay such as a Sleep -1 or a WinWait for a window that does not yet exist.

In v1.0.40.01+, a critical thread becomes interruptible when a MsgBox or other dialog is displayed. However, unlike "Thread Interrupt", the thread becomes critical again after the user dismisses the dialog.

Because Critical is a thread-specific setting, when a critical thread ends, the underlying/resumed thread (if any) will automatically be noncritical. Consequently, there is no need to do "Critical Off" right before ending a thread.

If Critical is not used in the auto-execute section (top part of the script), all threads start off as noncritical (though the settings of "Thread Interrupt" will still apply). By contrast, if the auto-execute section turns on Critical but never turns it off, every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off critical.

The command "Thread NoTimers" is similar to Critical except that it prevents interruptions from timers only.

Related

Thread (command), Threads, #MaxThreadsPerHotkey, #MaxThreadsBuffer, OnMessage, Hotkey, Menu, SetTimer

Example

#space::  ; Win+Space hotkey.
Critical
ToolTip No new threads will launch until after this ToolTip disappears.
Sleep 3000
ToolTip  ; Turn off the tip.
return  ; Returning from a hotkey subroutine ends the thread. Any underlying thread to be resumed is noncritical by definition.